//
//  XQLoginViewController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/20.
//

#import "XQLoginViewController.h"
#import "XQLoginPhoneView.h"
#import "XQLoginCodeView.h"

@interface XQLoginViewController ()
@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) UIImageView *logoImageView;
@property (nonatomic,strong) UILabel *nameLb;
@property (nonatomic,strong) XQLoginPhoneView *phoneView;
@property (nonatomic,strong) XQLoginCodeView *codeView;
@property (nonatomic,strong) UIImageView *voiceImageView;
@property (nonatomic,strong) UILabel *voiceLb;
@property (nonatomic,strong) UIButton *voiceBtn;
@property (nonatomic,strong) UIButton *radioButton;
@property (nonatomic,strong) UILabel *privacyLb;
@property (nonatomic,strong) UIButton *privacyBtn;
@property (nonatomic,strong) UIButton *loginBtn;
@property (nonatomic,copy) NSString *phoneText;
@property (nonatomic,copy) NSString *codeText;

@end

@implementation XQLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeNav];
    [self makeUI];
    [self makeConstraints];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startLocation];
    
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self stopLocation];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)makeNav {
    self.navigationBar.backgroundColor = [UIColor clearColor];
    [self.navigationBar setTitleColor:[UIColor whiteColor]];
    [self.navigationBar setTitle:@"Sign in"];
    [self.navigationBar setBackImageName:@"login_back"];
}

- (void)makeUI {
    [self.view insertSubview:self.imageView belowSubview:self.navigationBar];
    [self.imageView addSubview:self.logoImageView];
    [self.imageView addSubview:self.nameLb];
    [self.imageView addSubview:self.phoneView];
    [self.imageView addSubview:self.codeView];
    [self.imageView addSubview:self.voiceImageView];
    [self.imageView addSubview:self.voiceLb];
    [self.imageView addSubview:self.voiceBtn];
    [self.imageView addSubview:self.radioButton];
    [self.imageView addSubview:self.privacyLb];
    [self.imageView addSubview:self.privacyBtn];
    [self.imageView addSubview:self.loginBtn];
}

- (void)makeConstraints {
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([UIScreen mainScreen].topHeight + 14);
        make.left.equalTo(@18);
        make.width.height.equalTo(@36);
    }];
    [self.nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.logoImageView);
        make.left.equalTo(self.logoImageView.mas_right).offset(15);
    }];
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.logoImageView.mas_bottom).offset(26);
        make.left.right.equalTo(@0);
    }];
    [self.codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.phoneView.mas_bottom).offset(20);
        make.left.right.equalTo(@0);
    }];
    [self.voiceLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.codeView.mas_bottom).offset(19);
        make.right.equalTo(@-28);
    }];
    [self.voiceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.voiceLb);
        make.width.height.mas_equalTo(20);
        make.right.equalTo(self.voiceLb.mas_left).offset(-6);
    }];
    [self.voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.voiceImageView.mas_top);
        make.left.equalTo(self.voiceImageView.mas_left);
        make.bottom.equalTo(self.voiceImageView.mas_bottom);
        make.right.equalTo(self.voiceLb.mas_right);
    }];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-[UIScreen mainScreen].bottomHeight - 128);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.height.mas_equalTo(45);
    }];
    [self.radioButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.loginBtn.mas_top).offset(-20);
        make.left.equalTo(@29);
        make.width.height.mas_equalTo(16);
    }];
    [self.privacyLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.radioButton.mas_right).offset(6.5);
        make.centerY.equalTo(self.radioButton);
    }];
    [self.privacyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.radioButton);
        make.left.equalTo(self.privacyLb.mas_right);
        make.right.lessThanOrEqualTo(@0);
    }];
}

#pragma mark - private

- (void)radioClick {
    self.radioButton.selected = !self.radioButton.selected;
    [self updateLoginStatus];
}

- (void)updateLoginStatus {
    bool flag = self.phoneText.length > 0 && self.codeText.length > 0 && self.radioButton.selected;
    if (flag) {
        [_loginBtn setTitleColor:kMainTextColor forState:UIControlStateNormal];
    }else {
        [_loginBtn setTitleColor:[kMainTextColor colorWithAlphaComponent:0.5] forState:UIControlStateNormal];
    }
}

- (void)voiceClick {
    
    if (self.phoneText.length == 0) {
        [XQToast showMsg:@"Please enter your phone number"];
        return;
    }
    
    if (self.startInterval == 0) {
        self.startInterval = [XQTimeTool nowTimeStamp];
    }
    
    NSDictionary *dic = @{
        @"monitoring" : self.phoneText
    };
            
    [XQHUD showLoadingInView:self.view];
    @weakify(self);
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/balloons"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if (!error) {
            if ([responseObject[@"concept"] integerValue] == 0) {
                [self.codeView becomeFirstResponder];
            }
            [XQToast showMsg:responseObject[@"loon"]];
        }else {
            [XQToast showMsg:@"Network Connection Error"];
        }
    }];
}

- (void)phoneTextFieldHandle:(NSString *)text {
    self.phoneText = text;
    [self updateLoginStatus];
}

- (void)codeTextFieldHandle:(NSString *)text {
    self.codeText = text;
    [self updateLoginStatus];
}

- (void)sendClick {
    if (self.phoneText.length == 0) {
        [XQToast showMsg:@"Please enter your phone number"];
    }else {
        
        if (self.startInterval == 0) {
            self.startInterval = [XQTimeTool nowTimeStamp];
        }
        
        NSDictionary *dic = @{
            @"monitoring" : self.phoneText
        };
                
        [XQHUD showLoadingInView:self.view];
        @weakify(self)
        [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/stratosphere"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
            @strongify(self);
            [XQHUD hideLoadindInView:self.view];
            NSLog(@"%@",responseObject);
            if (!error) {
                if ([responseObject[@"concept"] integerValue] == 0) {
                    [self.codeView.sendBtn stop];
                    [self.codeView.sendBtn start];
                    [self.codeView becomeFirstResponder];
                }
                [XQToast showMsg:responseObject[@"loon"]];
            }else {
                [XQToast showMsg:@"Network Connection Error"];
            }
        }];
    }
}

- (void)loginClick {
    if (self.phoneText.length == 0) {
        [XQToast showMsg:@"Please enter your phone number"];
        return;
    }
    if (self.codeText.length == 0) {
        [XQToast showMsg:@"Please enter the verification code"];
        return;
    }
    if (!self.radioButton.isSelected) {
        [XQToast showMsg:@"Please read and agree to the Privacy Policy"];
        return;
    }
    
    NSDictionary *dic = @{
        @"asset" : [NSString stringWithFormat:@"%@",self.phoneText],
        @"orbcomm" : self.codeText
    };
            
    @weakify(self);
    [XQHUD showLoadingInView:self.view];
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/concept"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if ([responseObject[@"concept"] integerValue] == 0) {
            NSDictionary *dic = responseObject[@"accomplish"];
            
            if ([dic[@"continuous"] description].length != 0) {
                [[NSUserDefaults standardUserDefaults] setObject:dic[@"continuous"] forKey:@"continuous"];
               [[XQNetManager sharedInstance].globalDic setValue:dic[@"continuous"] forKey:@"continuous"];
            }
            
            [self reportRisk];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [XQToast showMsg:responseObject[@"loon"]];
            [self.codeView clear];
        }
    }];
}

- (void)hideKeyboard {
    [self.view endEditing:YES];
}

- (void)reportRisk {
    self.endInterval = [XQTimeTool nowTimeStamp];
    [XQGoogleMarket reportRiskWithType:@"1" longitude:self.longitude latitude:self.latitude startTime:self.startInterval endTime:self.endInterval orderId:@""];
}

- (void)privacyClick {
    XQWebViewController *controller = [XQWebViewController new];
    controller.url = [XQNetManager getWebUrlAbsolutePath:[XQToolManager manager].loginProtocol];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - lazy

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.image = [UIImage imageNamed:@"login_bg"];
        [_imageView setUserInteractionEnabled:YES];
        [_imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)]];
    }
    return _imageView;
}


- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = [[UIImageView alloc] init];
        _logoImageView.image = [UIImage imageNamed:@"login_logo"];
    }
    return _logoImageView;
}

- (UILabel *)nameLb {
    if (!_nameLb) {
        _nameLb = [[UILabel alloc] init];
        _nameLb.text = @"JoinPeso";
        _nameLb.textColor = kMainTextColor;
        _nameLb.font = [UIFont boldSystemFontOfSize:26];
    }
    return _nameLb;
}

- (XQLoginPhoneView *)phoneView {
    if (!_phoneView) {
        _phoneView = [[XQLoginPhoneView alloc] init];
        @weakify(self)
        _phoneView.textFielHandle = ^(NSString * _Nonnull text) {
            @strongify(self);
            [self phoneTextFieldHandle:text];
        };
    }
    return _phoneView;
}

- (XQLoginCodeView *)codeView {
    if (!_codeView) {
        _codeView = [[XQLoginCodeView alloc] init];
        @weakify(self)
        _codeView.textFielHandle = ^(NSString * _Nonnull text) {
            @strongify(self);
            [self codeTextFieldHandle:text];
        };
        _codeView.sendHandle = ^{
            @strongify(self);
            [self sendClick];
        };
    }
    return _codeView;
}

- (UIImageView *)voiceImageView {
    if (!_voiceImageView) {
        _voiceImageView = [[UIImageView alloc] init];
        _voiceImageView.image = [UIImage imageNamed:@"login_voice"];
    }
    return _voiceImageView;
}

- (UILabel *)voiceLb {
    if (!_voiceLb) {
        _voiceLb = [[UILabel alloc] init];
        _voiceLb.text = @"Voice verification";
        _voiceLb.textColor = kMainTextColor;
        _voiceLb.font = [UIFont systemFontOfSize:12];
    }
    return _voiceLb;
}

- (UIButton *)voiceBtn {
    if (!_voiceBtn) {
        _voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_voiceBtn addTarget:self action:@selector(voiceClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _voiceBtn;
}

- (UIButton *)radioButton {
    if (!_radioButton) {
        _radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _radioButton.selected = YES;
        [_radioButton setImage:[UIImage imageNamed:@"login_radio_unselect"] forState:UIControlStateNormal];
        [_radioButton setImage:[UIImage imageNamed:@"login_radio_select"] forState:UIControlStateSelected];
        [_radioButton addTarget:self action:@selector(radioClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _radioButton;
}

- (UILabel *)privacyLb {
    if (!_privacyLb) {
        _privacyLb = [[UILabel alloc] init];
        _privacyLb.text = @"I have read and agree with";
        _privacyLb.textColor = kMainTextColor;
        _privacyLb.font = [UIFont systemFontOfSize:13];
    }
    return _privacyLb;
}

- (UIButton *)privacyBtn {
    if (!_privacyBtn) {
        _privacyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_privacyBtn setTitle:@"<Privacy agreement>" forState:UIControlStateNormal];
        [_privacyBtn setTitleColor:kBlueTextColor forState:UIControlStateNormal];
        _privacyBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_privacyBtn addTarget:self action:@selector(privacyClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _privacyBtn;
}

- (UIButton *)loginBtn {
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginBtn setTitle:@"Login" forState:UIControlStateNormal];
        _loginBtn.layer.cornerRadius = 22.5;
        _loginBtn.backgroundColor = kOrangeColor;
        [_loginBtn setTitleColor:[kMainTextColor colorWithAlphaComponent:0.5] forState:UIControlStateDisabled];
        [_loginBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
        _loginBtn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    }
    return _loginBtn;
}

@end
